<template>
  <div>
    <basic-container>
      <avue-crud
        :option="tableOption"
        :data="tableData"
        :table-loading="tableLoading"
        :page="page"
        ref="crud"
        @row-save="handleSave"
        @selection-change="handleSelectionChange"
        @row-update="handleUpdate"
        @search-change="handleSearchChange"
      >
        <template slot="menuLeft">
          <el-button
            type="danger"
            @click="handleRowDel"
            :loading="bachDeleting"
            icon="el-icon-remove"
            v-perm="'/admin/role/batch-remove'"
            size="small"
          >批量删除</el-button>
        </template>
        <template slot-scope="scope" slot="menu">
          <el-button
            icon="el-icon-edit"
            type="primary"
            size="small"
            v-perm="'/admin/role/edit'"
            @click="$refs.crud.rowEdit(scope.row,scope.index)"
          >修改</el-button>
          <el-button
            icon="el-icon-remove"
            type="danger"
            v-perm="'/admin/role/remove'"
            size="small"
            @click="handleDel(scope.row,scope.index)"
          >删除</el-button>
          <el-button
            icon="el-icon-check"
            size="small"
            v-perm="'/admin/role/power'"
            @click="handleGrade(scope.row,scope.$index)"
          >权限</el-button>
        </template>
      </avue-crud>
      <el-dialog title="菜单" :visible.sync="grade.box" width="40%" append-to-body>
        <div style="height:600px;overflow:auto;">
          <el-tree
            :data="allMenuData"
            :expand-on-click-node="false"
            :default-checked-keys="grade.check"
            show-checkbox
            node-key="name"
            default-expand-all
            ref="nodeTree"
          ></el-tree>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button :loading="isUpdatingGrade" type="primary" @click="handleGradeUpdate">更新</el-button>
        </span>
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { validatenull } from "@/util/validate";
import {
  getRoleData,
  updateRoleData,
  createRoleData,
  removeRoleById,
  queryRoleCodeList,
  saveRoleCodeList
} from "../../../api/admin";
import { roleOption } from "@/const/admin/adminTabelOption.js";
import { deepClone } from "../../../util/util";
export default {
  name: "role",
  components: {},
  data() {
    return {
      bachDeleting: false,
      tableOption: {}, //表格设置属性
      tableData: [], //表格的数据
      tablePage: 1,
      tableLoading: false,
      isUpdatingGrade: false,
      tableQueryParam: {},
      page: {
        total: 0, //总页数
        currentPage: 1, //当前页数
        pageSize: 10 //每页显示多少条
      },
      grade: {
        box: false,
        check: []
      }
    };
  },
  created() {
    //初始化数据格式
    this.tableOption = roleOption;
    this.handleList();
  },
  watch: {},
  mounted() {},
  computed: {
    ...mapGetters(["permission", "menuAll", "allPermission"]),
    allMenuData() {
      return this.calMenus(deepClone(this.menuAll));
    }
  },
  props: {},
  methods: {
    calMenus(items) {
      for (let i = 0; i < items.length; i++) {
        const item = items[i];
        if (item.children && item.children.length > 0) {
          item.children = this.calMenus(item.children);
        } else {
          if (item.buttons && item.buttons.length) {
            item.children = item.buttons;
          }
        }
      }
      return items;
    },
    handleSelectionChange(args) {
      this.currentSelectedRowIds = args.map(el => el.Id);
    },
    /**
     * @title 权限更新
     *
     **/
    handleGradeUpdate() {
      this.isUpdatingGrade = true;
      this.grade.check = this.$refs.nodeTree
        .getCheckedKeys(false)
        .concat(this.$refs.nodeTree.getHalfCheckedKeys());
      saveRoleCodeList(this.currentRole.Id, this.grade.check)
        .then(() => {
          this.isUpdatingGrade = false;
          this.$refs.nodeTree.setCheckedKeys([]);
          this.grade.check = [];
          this.grade.box = false;
          this.showSuccess();
        })
        .catch(() => {
          this.isUpdatingGrade = false;
        });
    },
    handleSearchChange(params) {
      this.tableQueryParam = params;
      this.handleList();
    },
    handleRowDel() {
      if (validatenull(this.currentSelectedRowIds)) {
        this.$notify({
          showClose: true,
          message: "请至少选择一行要删除的数据",
          type: "error"
        });
        return false;
      }
      this.bachDeleting = true;
      removeRoleById(this.currentSelectedRowIds)
        .then(() => {
          this.bachDeleting = false;
          this.$refs.crud.selectClear();
          this.$message({
            showClose: true,
            message: "成功",
            type: "success"
          });
        })
        .catch(() => {
          this.bachDeleting = false;
        });
    },
    /**
     * @title 权限选择
     *
     **/
    handleGradeCheckChange(data, checked) {
      if (checked) {
        this.grade.check.push(data.name);
      } else {
        this.grade.check.splice(this.grade.check.indexOf(data.name), 1);
      }
    },
    /**
     * @title 打开权限
     */
    handleGrade(row) {
      this.currentRole = row;
      queryRoleCodeList(row.Id).then(data => {
        data = data || [];
        this.grade.box = true;
        this.grade.check = (data || []).filter(el => this.allPermission[el]);
        this.$nextTick(() => {
          this.$refs.nodeTree.setCheckedKeys(this.grade.check);
        });
      });
    },
    /**
     * @title 打开新增窗口
     * @detail 调用crud的handleadd方法即可
     *
     **/
    handleAdd() {
      this.$refs.crud.rowAdd();
    },
    /**
     * @title 获取数据
     * @detail 赋值为tableData表格即可
     *
     **/
    handleList() {
      this.tableLoading = true;
      getRoleData({
        pageNo: this.page.currentPage,
        pageSize: this.page.pageSize,
        ...this.tableQueryParam
      })
        .then(data => {
          this.tableData = data.rows;
          this.page.total = data.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    /**
     * @title 数据添加
     * @param row 为当前的数据
     * @param done 为表单关闭函数
     *
     **/
    handleSave(row, done, reject) {
      createRoleData(row)
        .then(() => {
          this.handleList();
          this.$message({
            showClose: true,
            message: "添加成功",
            type: "success"
          });
          done();
        })
        .catch(() => {
          reject();
        });
    },
    /**
     * @title 数据删除
     * @param row 为当前的数据
     * @param index 为当前更新数据的行数
     *
     **/
    handleDel(row, index) {
      this.$confirm(`是否确认删除序号为${index + 1}`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          removeRoleById([row.Id]).then(() => {
            this.handleList();
            this.$refs.crud.selectClear();
            this.$message({
              showClose: true,
              message: "删除成功",
              type: "success"
            });
          });
        })
        .catch(() => {});
    },
    /**
     * @title 数据更新
     * @param row 为当前的数据
     * @param index 为当前更新数据的行数
     * @param done 为表单关闭函数
     *
     **/
    handleUpdate(row, index, done, reject) {
      // this.tableData.splice(index, 1, row);
      updateRoleData(row)
        .then(() => {
          this.handleList();
          this.$message({
            showClose: true,
            message: "修改成功",
            type: "success"
          });
          done();
        })
        .catch(() => {
          reject();
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.table-container {
  padding: 8px 10px;
}
</style>
